<?php

namespace mybackend\controllers;

use common\entities\myhtsq\DocumentEntity;
use common\models\myhtsq\ContractReceivableModel;
use common\models\myhtsq\InvoiceModel;
use common\repositories\myhtsq\ApplicationInfoRepository;
use common\repositories\myhtsq\BussAccountTypesRepository;
use common\repositories\myhtsq\ContractApplicationRepository;
use common\repositories\myhtsq\ContractCompanyRepository;
use common\repositories\myhtsq\ContractLittlerCategoryRepository;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ContractPropertyRepository;
use common\repositories\myhtsq\DocumentRepository;
use common\services\myhtsq\ContractReceivableService;
use common\services\myhtsq\ContractService;
use common\services\myhtsq\ErpInterfaceService;
use common\entities\myhtsq\ContractPropertyEntity;
use common\entities\myhtsq\ContractCompanyEntity;
use common\entities\myhtsq\ContractManageEntity;
use common\repositories\common\MyscrmContractApplicationRepository;
use common\entities\myhtsq\ContractLittlerCategoryEntity;
use common\entities\myhtsq\ApplicationInfoEntity;
use common\repositories\myhtsq\ContractAccountCompanyRepository;
use common\support\Helper;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use Yii;
use common\traits\LogActionTrait;
use common\entities\ContractEntity;
use mybackend\controllers\ContractController;
use common\support\StringHelper;


class ChannelController extends BaseController {

    use LogActionTrait;
    use \common\error\ReturnErrorTrait;

    protected $_allowAction = [
        'update-origin-app-list',
        'add-achievement-grouping',
        'add-achievement-data'
    ];

    protected $_contractService;
    protected $_contractReceivableService;
    private $_key = "reyyu7^uujw$@!&*h@123&";

    private $yunkeFinance = '云客签约-直属';

    private $mingyuanFinance = '明源签约-直属';

    public function __construct($id, $module, ContractService $contractService, ContractReceivableService $contractReceivableService, $config = []) {
        $this->_contractService = $contractService;
        $this->_contractReceivableService = $contractReceivableService;
        parent::__construct($id, $module, $config);
    }


    public function beforeAction($action) {
        $this->logAction($action);
        $now = Yii::$app->request->request('now');
        $section = Yii::$app->request->request('section');
        $action  = Yii::$app->controller->action->id;
        if(! in_array($action, $this->_allowAction)){
            if (abs($now - time()) > 86400) {
                $this->exportJson([], 1, "已过期！");
                exit;
            }
            if (empty($now) || empty($section)) {
                $this->exportJson([], 2, "参数错误！");
                exit;
            }

            if (substr(md5($this->_key . $now), '2', '20') != $section) {
                $this->exportJson([], 3, "非法操作！");
                exit;
            }
        }

        return true;
    }

    /**
     * 合同数据接口
     */
    public function actionGetContractInfo() {
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');
        $contractGuid = Yii::$app->request->request('contractGuid');

        $data = $this->_contractService->getContractListByTime($beginTime, $endTime, $contractGuid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 合同返款数据接口
     */
    public function actionGetContractFk()
    {
        $contractGuid = Yii::$app->request->request('contractGuid');

        $data = $this->_contractService->getContractFkList($contractGuid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 合同数据接口
     */
    public function actionGetContractInfoNoAsFields() {
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');

        $data = $this->_contractService->getContractListByTimeNoAsFields($beginTime, $endTime);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 签约业绩接口
     */
    public function actionGetSignAchievements() {
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');

        $data = $this->_contractService->getSignAchievementsByTime($beginTime, $endTime);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 回款信息接口
     */
    public function actionGetPaymentInfo() {
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');
        $contractGuid = Yii::$app->request->request('contractGuid');

        $data = $this->_contractService->getPaymentInfoByTime($beginTime, $endTime, $contractGuid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 产品信息
     */
    public function actionGetProductInfo(){
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');
        $contractGuid = Yii::$app->request->request('contractGuid');

        $data = $this->_contractService->getProductInfoByTime($beginTime, $endTime, $contractGuid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 发票信息
     */
    public function actionGetInvoices() {
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');
        $contractGuid = Yii::$app->request->request('contractGuid');

        $data = $this->_contractService->getInvoicesByTime($beginTime, $endTime, $contractGuid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 发票摘要信息
     */
    public function actionGetInvoicesAbstract() {
        $data = $this->_contractService->getInvoiceAllSummary();
        if(! empty($data)) {
            foreach ($data as $index => $value) {
                unset($data[$index]['summary_id']);
            }
        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存发票
     */
    public function actionSaveInvoiceReceivable()
    {
        $invoiceData = Yii::$app->request->request('invoiceModel', '');
        $invoiceData = json_decode($invoiceData, true);

        if(empty($invoiceData)){
            $this->exportJson('', $this->_contractReceivableService->getErrCode(), 'invoiceModel字段不能为空');
        }

        $invoiceModel = new InvoiceModel(['scenario' => 'saveinvoice']);
        if ($invoiceModel->load($invoiceData, '')) {
            $invoiceModel->is_sync = 1;
            $result = $this->_contractReceivableService->saveInvoiceReceivable($invoiceModel);
            $this->exportJson($result, $this->_contractReceivableService->getErrCode(), $this->_contractReceivableService->getErrMsg());
        } else {
            $this->errorParam();
        }
    }

    /**
     * 出库信息
     */
    public function actionGetOrganizationInfo(){
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');
        $contractGuid = Yii::$app->request->request('contractGuid');

        $data = $this->_contractService->getGetOrganizationInfoByTime($beginTime, $endTime, $contractGuid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 款项发票回款关联表
     */
    public function actionGetInvoicePayment(){
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');
        $contractGuid = Yii::$app->request->request('contractGuid');

        $data = $this->_contractService->getInvoicePaymentByTime($beginTime, $endTime, $contractGuid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 应收款表
     */
    public function actionGetReceivableInfo(){
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');
        $contractGuid = Yii::$app->request->request('contractGuid');

        $data = $this->_contractService->getReceivableInfoByTime($beginTime, $endTime, $contractGuid);

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取单个合同的应收款
     */
    public function actionGetContractReceivableInfo(){
        $beginTime  = Yii::$app->request->request('beginTime');
        $endTime    = Yii::$app->request->request('endTime');
        $contractId = Yii::$app->request->request('contractId');

        $data = $this->_contractService->getReceivableInfoByTime($beginTime, $endTime, $contractId);

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 收入数据接口
     */
    public function actionGetRevenueInfo() {
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');

        $data = $this->_contractService->getRevenueInfoByTime($beginTime, $endTime);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 设置缓存
     */
    public function actionSetCache() {
        $key = Yii::$app->request->request('key');
        $value = Yii::$app->request->request('value');
        if (empty($key) || empty($value)) {
            die('no key or no value');
        }
        $time = empty(Yii::$app->request->request('time')) ? 60 : Yii::$app->request->request('time');
        $ret = Yii::$app->cache->set($key, $value, $time);
        $this->exportJson('ok', $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 关闭缓存
     * @param type $key
     */
    public function actionGetCache($key) {
        $key = Yii::$app->request->request('key');
        if (empty($key)) {
            die('no key');
        }
        $value = Yii::$app->cache->get($key);
        $this->exportJson($value, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取ERP信息
     * @param $contract
     * @return mixed
     */
    private function getErpSignUserData($contract){
        if(! empty($contract['sign_people_id'])){
            /** @var ErpInterfaceService $erpInterfaceService */
            $erpInterfaceService = Yii::createObject(ErpInterfaceService::className());
            $signUserData = $erpInterfaceService->getUserInfoById($contract['sign_people_id']);
            $contract['area_id'] = $signUserData['BUGUID'];             //合同所属区域ID
            $contract['area_name'] = $signUserData['CompanyName'];      //合同所属区域名称
            $contract['area_code'] = $signUserData['BUCode'];
            $contract['sign_people_department_by'] = $signUserData['DepartmentGUID'];       //签约人部门id
            $contract['sign_people_department_name'] = $signUserData['DepartmentName'];     //签约人部门名称

        }

        return $contract;
    }

    /**
     * 获取产品的外部参数
     *
     * @return array|mixed
     */
    private function getContractProductParams($type)
    {
        $productInfoData = Yii::$app->request->request('productinfo');
        if($productInfoData){
            $productInfo = json_decode($productInfoData, true);
            $productInfo = $this->convertContractProductInfo($productInfo, $type);
        } else {
            $productInfo = [];
        }

        return $productInfo;
    }

    /**
     * 获取合同的应收款参数
     *
     * @return    array|mixed
     */
    private function getContractReceivableParams(){
        // 应收款
        $receivableData = Yii::$app->request->request('receivable');
        if($receivableData){
            $receivable = json_decode($receivableData, true);
        }else{
            $receivable = [];
        }

        return $receivable;
    }

    /**
     * 获取文档的外部参数
     *
     * @return array|mixed
     */
    private function getContractDocParams($type)
    {
        $docInfoData = Yii::$app->request->request('docinfo');
        if($docInfoData){
            $docInfo = json_decode($docInfoData, true);
            $docInfo = $this->convertContractDocInfo($docInfo, $type);
        } else {
            $docInfo = [];
        }

        return $docInfo;
    }

    /**
     * 获取合同的外部参数
     * 注意该方法只有从ERP入参的合同使用，因此erp_contract_id就是contract_id
     *
     * @return array|mixed
     */
    private function getContractParams($contractStatus = 0, $financeType = '云客签约-直属')
    {
        // 合同
        $contractData = Yii::$app->request->post('contract');
        Yii::info($contractData,'channel');
        $contract = json_decode($contractData, true);

        if(! empty($contract)){
            $contract['contract_property_id'] = $this->getContractPropertyId($contract);                //合同性质的ID
            $contract['company_id']           = $this->getContractCompanyId($contract);                 //签署公司ID
            $contract['littler_category_id']  = $this->getContractCategoryId($contract);                //合同小分类ID
            $contract['erp_contract_code']    = isset($contract['contract_code']) ? $contract['contract_code'] : '';  //关联ERP合同编号

            $contract['input_date']           = isset($contract['contract_entry_date'])     ? $contract['contract_entry_date'] : '';          //合同录入时间
            $contract['effect_date']          = isset($contract['contract_effective_date']) ? $contract['contract_effective_date'] : '';      //合同生效时间
            $contract['rent_amount']          = isset($contract['rentdeal_price'])          ? $contract['rentdeal_price']    : '';            //租用成交价
            $contract['delivery_amount']      = isset($contract['deliverdeal_price'])       ? $contract['deliverdeal_price'] : '';            //交付成交价
            $contract['balance_amount']       = isset($contract['js_amount'])               ? $contract['js_amount']         : '0.0000';      //结算金额
            $contract['category_id']          = 'b011f523-fcf2-11e4-bed8-00155d02c832';//合同类别ID 由于商机系统那边没有此字段，故默认为“云客租用服务合同”
            $contract['big_category_id']      = '2ae79470-fcf3-11e4-bed8-00155d02c832';//合同大类ID 由于商机系统那边没有此字段，故默认为“服务合同”
            $contract['attribute_name']       = 'true,false,false';//由于商机系统那边没有此字段，故默认为“新增”
            $contract['erp_contract_id']      = $contract['contract_id'];

            /** @var ErpInterfaceService $erpInterfaceService */
            $contract = $this->getErpSignUserData($contract);

            $contract['contract_status'] = $contractStatus;

            $contract['from_finance'] = $this->getContractFromFinance($financeType);
            $contract['from_performance_finance'] = $this->getContractFromPerformanceFinance($financeType);

        }

        return $contract;
    }

    /**
     * 合同变更接口
     */
    public function actionAddContractEkpDraft(){
        // 合同
        $contract = $this->getContractParams(0, '明源签约-直属');

        $model = $this->_contractService->getErpContractId($contract['erp_contract_id']);
        if(empty($model)){
            //如果不存关联的ERP合同，则插入草稿合同

            //合同变更的合同ID不能与ERP合同ID一致
            $contract['contract_id'] = StringHelper::uuid();

            // 合同产品
            $productInfo = $this->getContractProductParams('add');

            //文档
            $docInfo = $this->getContractDocParams('add');

            $result = $this->_contractService->doInsertFromBusinessSystem($contract, [], $productInfo, [], $docInfo);
        } else {
            //存在则强制更新合同

            $contract['contract_id'] = $model->contract_id;
            unset($contract['contract_status']);

            //TMD 脑残写的 $contract_code会被覆盖
            unset($contract['contract_code']);
            $contract['contract_code'] = $model->contract_code;

            // 合同产品
            $productInfo = $this->getContractProductParams('update');
            $productInfo = $this->getContractApplicationInfo($contract['contract_id'], $productInfo);

            //文档
            $docInfo = $this->getContractDocParams('update');
            $docInfo = $this->getContractDocInfo($contract['contract_id'], $docInfo);

            $result = $this->_contractService->doUpdateFromBusinessSystem($contract, $productInfo, $docInfo);
        }

        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 新增草稿合同
     */
    public function actionAddContractDraft()
    {
        $contract = $this->getContractParams(0, $this->yunkeFinance);

        // 应收款
        $receivable = $this->getContractReceivableParams();

        // 合同产品
        $productInfo = $this->getContractProductParams('add');

        //不接收收入
        $incomeInfo = [];

        //文档
        $docInfo = $this->getContractDocParams('add');

        $result = $this->_contractService->doInsertFromBusinessSystem($contract, $receivable, $productInfo, $incomeInfo, $docInfo);

        if($result === true){
            //增加业绩信息
            $this->addAchievementData('add', $contract['contract_id']);

            //业绩分组
            $this->_contractService->achievementGrouping($contract['contract_id']);

            //更新合同结算金额  zhoud的增加业绩信息的方法会修改结算金额，而接口已EKP推送的金额为准
            if(isset($contract['js_amount'])) {
                $this->updateBalanceAmount($contract);
            }
        }

        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }



    /**
     * 新增业绩信息
     */
    public function actionAddAchievementData()
    {
        $id = \Yii::$app->request->request('id');
        $result = true;

        if(! empty($id)){
            $result = $this->addAchievementData('add', $id);
        }

        $this->exportJson($result);
    }

    /**
     * 新增业绩汇总
     */
    public function actionAddAchievementGrouping()
    {
        $id = \Yii::$app->request->request('id');
        $result = true;

        if(! empty($id)){
            $result = $this->_contractService->achievementGrouping($id);
        }

        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取EKP的产品主数据
     */
    public function actionUpdateOriginAppList(){
        //ekp的接口缓慢
        set_time_limit(600);

        $erpAppList   = ErpInterfaceService::getApplicationList();
        $yunKeAppList = $this->getYunKeByOriginAppList($erpAppList);

        $appIdList    = $this->getAppIdList($yunKeAppList);

        //本地数据
        $localAppList = ApplicationInfoRepository::getApplicationInfoByApplicationIds($appIdList);
        $existsLocalAppIdList = ArrayHelper::getColumn($localAppList, 'application_id');

        //远程数据
        $remoteYunKeAppInfoList = $this->convertEkpAppToYunkeField($yunKeAppList);

        //整合数据集
        $spliceResult = $this->spliceAddOrUpdateAppList($existsLocalAppIdList, $remoteYunKeAppInfoList);
        $spliceLocalAppList = $this->convertAppToList($localAppList);

        $spliceAddList    = $spliceResult['addList'];
        $spliceUpdateList = $spliceResult['updateList'];

        //待处理的数据库集合
        $dbAddList    = $this->convertAppToList($spliceAddList);
        $dbUpdateList = $this->getDiffAppToList($spliceLocalAppList, $this->convertAppToList($spliceUpdateList));

        //处理数据集合的后置操作
        $dbAddList    = $this->afterAppToList(['appResult', 'priceResult'], $dbAddList, 'add');
        $dbUpdateList = $this->afterAppToList(['appResult', 'priceResult'], $dbUpdateList, 'update');

        //执行数据库操作
        $result = $this->handleAppData($dbAddList, $dbUpdateList);

        $this->exportJson($result);
    }

    /**
     * 对产品主数据进行数据库操作
     * @param     $addList    array  新增数据源
     * @param     $updateList array  更新数据源
     * @return    array
     */
    private function handleAppData($addList, $updateList){
        return [
            'addResult'    => ApplicationInfoRepository::addApplication($addList),
            'updateResult' => ApplicationInfoRepository::updateApplication($updateList),
        ];
    }


    /**
     * 获取差异的产品主数据到列表
     *
     * @param     $spliceLocalLocal array 整合后的本地数据源
     * @param     $remoteUpdateList array 整合后的远程数据源
     * @return    array
     */
    private function getDiffAppToList($spliceLocalLocal, $remoteUpdateList){
        $result = [];
        if(! empty($spliceLocalLocal) && ! empty($remoteUpdateList)){
            $remoteUpdateIndexList = [
                'appResult'    => ArrayHelper::index($remoteUpdateList['appResult'], 'application_id'),
                'priceResult'  => ArrayHelper::index($remoteUpdateList['priceResult'], 'application_id'),
            ];

            $result = [
                'appResult'   => $this->spliceDiffList('appResult', $spliceLocalLocal, $remoteUpdateIndexList),
                'priceResult' => $this->spliceDiffList('priceResult', $spliceLocalLocal, $remoteUpdateIndexList),
            ];
        }

        return $result;
    }

    /**
     * 拼接产品主数据的差异列表
     *
     * @param     $field      string 标志字段
     * @param     $localList  array  本地数据源
     * @param     $remoteList array  远程数据源
     * @return    array
     */
    private function spliceDiffList($field, $localList, $remoteList){
        $result = [];
        foreach ($localList[$field] as $value){
            if(isset($remoteList[$field][$value['application_id']]) &&
                ! empty(array_diff_assoc($value, $remoteList[$field][$value['application_id']]))){
                $result[] = $remoteList[$field][$value['application_id']];
            }
        }

        return $result;
    }

    /**
     * 拼接产品主数据的新增、修改列表
     *
     * @param     $existsLocalList          array 已存在的产品主数据ID集合
     * @param     $remoteYunKeAppInfoList   array 远程的产品主数据
     * @return    array
     */
    private function spliceAddOrUpdateAppList($existsLocalList, $remoteYunKeAppInfoList){
        $addList    = [];
        $updateList = [];
        foreach ($remoteYunKeAppInfoList as $value){
            if(in_array($value['application_id'], $existsLocalList)){
                $updateList[] = $value;
            } else {
                $addList[] = $value;
            }
        }

        return [
            'addList'    => $addList,
            'updateList' => $updateList,
        ];
    }


    /**
     * 获取产品主数据的ID集合
     *
     * @param     $list array 产品主数据
     * @return    array
     */
    private function getAppIdList($list){
        $result = [];
        if(! empty($list)){
            foreach ($list as $value){
                $result[] = $value['ProductID'];
            }
        }

        return $result;
    }

    /**
     * 转换EKP的产品主数据为云客的产品主数据字段
     *
     * @param     $list array 云客的产品主数据列表
     * @return    array
     */
    private function convertEkpAppToYunkeField($list){
        $result = [];
        if(! empty($list)){
            $appInfoField = [
                'ProductID'           => 'application_id',
                'ProductName'         => 'application_name',
                'BusinessTypeName'    => 'is_saas',
                'BenchmarkPrice'      => 'price',
                'LicensingStandards'  => 'unit',
                'IsOffShelf'          => 'is_off_shelf',
                'IncomeTypeName'      => 'revenue_type',
                'FinancialInComeType' => 'revenue_type_finance',
            ];

            $yunkeFields  = $this->getAppInfoYunkeField($list, $appInfoField);

            /* 转换业务收入项和财务收入项的值 */
            foreach ($yunkeFields as $value) {
                $bussId = BussAccountTypesRepository::getBussTypeIdByName($value['revenue_type'], $value['revenue_type_finance']);

                $value['buss_type_id'] = (! empty($bussId)) ? $bussId : '';

                $result[] = $value;
            }

        }

        return $result;
    }

    /**
     * 在产品主数据压入后进行后置操作
     *
     * @param     $field string 标志字段
     * @param     $list  array  数据源
     * @param     $type  string 操作类别
     * @return    mixed
     */
    private function afterAppToList($fields, $list, $type){
        if(! empty($fields)){
            foreach ($fields as $field){
                foreach($list[$field] as $key => $value){
                    switch ($type){
                        case 'add':
                            if($field == 'priceResult'){
                                $list[$field][$key]['price_id']   = StringHelper::uuid();
                            } else {
                                $list[$field][$key]['delivery_rules']    = 1;
                                $list[$field][$key]['provisioning_type'] = 2;
                                $list[$field][$key]['matching_rule']     = 3;
                            }

                            $list[$field][$key]['created_on'] = date('Y-m-d H:i:s');
                            $list[$field][$key]['created_by'] = 'ekp';
                            break;
                        case 'update':
                            $list[$field][$key]['modified_on'] = date('Y-m-d H:i:s');
                            $list[$field][$key]['modified_by'] = 'ekp';
                            break;
                    }

                }
            }
        }

        return $list;
    }


    /**
     * 转换产品主数据到列表
     *
     * @param $list
     */
    private function convertAppToList($list){
        $appResult = [];
        $priceResult = [];
        if(! empty($list)){
            foreach ($list as $value){
                $appResult[] = [
                    'application_id'   => $value['application_id'],
                    'application_name' => $value['application_name'],
                    'is_off_shelf'     => $value['is_off_shelf'],
                    'buss_type_id'     => $value['buss_type_id'],
                ];

                $priceResult[] = [
                    'application_id'   => $value['application_id'],
                    'price'            => $value['price'],
                    'unit'             => isset($value['unit']) ? $value['unit'] : '',
                ];
            }
        }

        return [
            'appResult'   => $appResult,
            'priceResult' => $priceResult,
        ];
    }

    /**
     * 获取合同产品的总数
     *
     * @param     $productInfo array 产品数据源
     * @return    int
     */
    private function getContractAppNum($productInfo){
        $result = 0;
        if(! empty($productInfo)){
            foreach ($productInfo as $value){
                if(isset($value['authorization_numeric'])){
                    $result += $value['authorization_numeric'];
                }
            }
        }

        return $result;
    }

    /**
     * 新增业绩信息
     *
     * @type      $type         string  操作类型
     * @param     $contractId   string  合同ID
     * @return    bool
     */
    private function addAchievementData($type, $contractId){
        $list          = ContractApplicationRepository::getAchievementData($contractId);
        $signPeopleId  = ContractManageRepository::getContractSignPeopleId($contractId);
        $establishTime = date('Y-m-d H:i:s');

        $result = true;
        try{
            foreach ($list as $value){
                $value['total_num']      = $value['authorization_numeric'];
                $value['establish_time'] = $establishTime;
                $value['contractId']     = 0;
                $value['AuthorId']       = empty($signPeopleId) ? 0 : $signPeopleId;

                //业绩信息
                $this->_contractService->achievementHandle($value, $type);
            }

        } catch (\Exception $e){
            $result = false;
            \Yii::error('添加业绩信息错误，合同ID：' . $contractId . '，错误原因：' . $e->getMessage());
        }

        return $result;
    }

    /**
     * 获取云客的产品主数据字段
     *
     * @param     $list         array 产品主数据
     * @param     $appInfoField array 云客主数据字段
     * @return    array
     */
    private function getAppInfoYunkeField($list, $appInfoField){
        $result = [];
        foreach ($appInfoField as $erpField => $yunKeField){
            foreach ($list as $key => $value){
                if(isset($value[$erpField])){
                    if($erpField == 'BusinessTypeName'){
                        $value[$erpField] = ($value[$erpField] == 'SAAS') ? 1 : 0;
                    }

                    $result[$key][$yunKeField] = $value[$erpField];
                }
            }
        }

        return $result;
    }

    /**
     * 通过EKP的主数据，获取云客的产品主数据列表
     *
     * @param     $list array 产品主数据列表
     * @return    array       云客产品主数据列表
     */
    private function getYunKeByOriginAppList($list){
        $result = [];
        if(! empty($list)){
            foreach ($list as $key => $value){
                if($value['ProductCategoriesName'] == '云客'){
                    $result[] = $value;
                }
            }
        }

        return $result;
    }

    /**
     * 获取签约产品的ID
     *
     * @param $contractId
     * @param $applicationId
     * @return bool|string
     */
    private function getContractApplicationInfo($contractId, $productInfo){
        foreach ($productInfo as $key => $value){
            $productInfo[$key]['contract_application_id'] = MyscrmContractApplicationRepository::getContractApplicationId($contractId, $value['application_id']);
        }

        return $productInfo;
    }

    /**
     * 获取文档合同信息
     *
     * @param $contractId
     * @param $docInfo
     * @return mixed
     */
    private function getContractDocInfo($contractId, $docInfo)
    {
        foreach ($docInfo as $key => $value){
            $docInfo[$key]['document_id'] = DocumentRepository::getDocumentId($contractId, trim($value['document_name']));
        }

        return $docInfo;
    }

    /**
     * 转换合同的文档信息
     *
     * @param  $docInfo 商机系统传的文档参数
     * @return array
     */
    private function convertContractDocInfo($docInfo, $type = 'add'){
        $config = array(
            '合同'       => 1,
            '战略协议'    => 2,
            '补充协议'    => 3,
            '标的物'      => 4,
            '质量评估表'  => 5,
            '审批邮件'    => 6,
        );

        foreach ($docInfo as $key => $value){
            if(isset($value['doc_name'])){
                $docInfo[$key]['__type'] = $type;
                $docInfo[$key]['document_name'] = $value['doc_name'];
                $docInfo[$key]['document_path'] = $value['doc_url'];
                $docInfo[$key]['document_type'] = isset($config[$value['doc_type']]) ? $config[$value['doc_type']] : 0;

                unset($docInfo[$key]['doc_url']);
                unset($docInfo[$key]['doc_type']);
                unset($docInfo[$key]['doc_name']);
            } else {
                unset($docInfo[$key]);
            }
        }

        return $docInfo;
    }

    /**
     * 转换合同产品的参数
     *
     * @param $productInfo  合同产品的参数
     * @return array
     */
    private function convertContractProductInfo($productInfo, $type = 'add'){
        if(! empty($productInfo)){
            $contractTypeConfig = [
                '新增' => 1,
                '增购' => 2,
                '续签' => 3,
            ];
            $block_app_from_epk_list = [
                'b85e2d92-613f-4751-9e22-63a87fc09550',//来访登记硬件服务
                'fdbc0d9c-276b-40fd-aa7a-c44d6501005b',//
                '2ff02359-dbb1-47bc-95d0-cff025003703',
                'f511bd38-477e-49c1-b6cb-d812d1c45eb9',
            ];
            Yii::info(var_export($productInfo,true),'channel');
            foreach ($productInfo as $key => $value){
                //需过滤掉EKP推过来的特定的产品
                if(in_array($value['product_id'],$block_app_from_epk_list)){
                    unset($productInfo[$key]);
                    continue;
                }
                $applicationInfo = $this->getContractProductInfo($value['product_id']);
                if(! empty($applicationInfo) && ! empty($applicationInfo['price'])){
                    //计算产品的标准总额
                    $applicationInfo['amount'] = round($value['number'] * $applicationInfo['price']['price'] * ($value['rent_time'] / 12));

                    $productInfo[$key] = array_merge($productInfo[$key], $applicationInfo);

                    $productInfo[$key]['contract_type'] = isset($contractTypeConfig[$value['contract_type']]) ? $contractTypeConfig[$value['contract_type']] : 1;
                    $productInfo[$key]['is_standard'] = 1;
                    $productInfo[$key]['__type'] = $type;
                }else {
                    $errorArr[] = $productInfo[$key]['product_name'];
                }

                // 将接口的字段改为我方的数据库字段名
                $productInfo[$key]['authorization_numeric'] = intval($value['number']);
                $productInfo[$key]['rent_period'] = isset($value['rent_time']) ? $value['rent_time'] : 0;

                unset($productInfo[$key]['product_id']);
                unset($productInfo[$key]['product_name']);
                unset($productInfo[$key]['price']);
                unset($productInfo[$key]['number']);
                unset($productInfo[$key]['rent_time']);
            }
        }

        if ($errorArr) {
            return $errorArr;
        }

        return $productInfo;
    }

    /**
     * 获取合同产品信息
     */
    private function getContractProductInfo($id){
        $result = ApplicationInfoRepository::getApplicationInfoByAppId($id);

        return $result;
    }


    /**
     * 更新应收款时间或责任人
     */
    public function actionUpdateContractReceivable()
    {
        $receivable_id = Yii::$app->request->request("receivable_id");
        //应收款日期
        $receivable_date = Yii::$app->request->request("receivable_date", "");
        //收款责任人
        $payee_id = Yii::$app->request->request("payee_id", "");

        if (empty($receivable_id)) {
            $this->exportJson([], -1, "参数错误！");
        }

        //收款责任人变更之后相应的 部门也变更
        /* @var $erpInterfaceService ErpInterfaceService */
        $erpInterfaceService = Yii::createObject(ErpInterfaceService::className());
        $erpUser = $erpInterfaceService->getUserInfoById($payee_id);
        $department_id = isset($erpUser["DepartmentGUID"]) ? $erpUser["DepartmentGUID"] : "";

        $data = [];
        $data["receivable_date"] = $receivable_date;
        $data["payee_id"] = $payee_id;
        $data["department_id"] = $department_id;

        $result = $this->_contractReceivableService->updateReceivableField($receivable_id, $data);
        $this->exportJson([], $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * erp 删除回款校验 给erp 用
     */

    public function actionErpDelPayment()
    {
        die;//此功能孟兵还未验证  f-20170711-htgl-erpapi 在该分支与测试环境待验证
        $payment_id = Yii::$app->request->request('payment_id');
        $del_payment = Yii::$app->request->request('del_payment');

        //$data = $this->_contractService->getInvoicePaymentByPaymentId($payment_id,$del_payment);
        //不接收$del_payment
        $data = $this->_contractService->getInvoicePaymentByPaymentId($payment_id);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 会签系统增加合同(报价单)
     */

    public function actionAddContractByQuote()
    {
        //TODO 依据参数填写相关信息生成一个合同
        //基本信息：1.客户信息,2.合同信息,3.产品信息,4.合同主责人
        //1.客户信息:客户简称 顶级客户简称 签约客户全称
        //2.合同信息：合同性质 合同签署公司 (原规则生成合同编号) 合同签署日期 合同录入日期 合同生效日期 合同签约人 合同所属区域
        //签约人所属部门 签约金额 产品租用金额/广告投放金额 交付金额/广告服务费
        //3.产品信息：产品名称(ID) 标准单价(每年,每项目) 产品数/短信条数 租用周期 标准总额 合同属性
        //4.合同主责人信息：(云客系统隐藏模块)

        //收入信息：
        //1.套账公司 2.核算收入类别 3.收入确认方式 4.收入项编码 5.收入金额 6.权益日期

        //应收信息：
        //1.签约金额 2.产品租用金 3.交付金额 4.已开票金额 5.已回款金额 //TODO 会签系统不生成标准固话字段
        //1.款项名称 2.款项小类 3.合同属性(不推送,默认为空) 4.关联收入项 5.应收金额 6.应收日期 7.收款责任人
        //8.收款责任部门(不推送,云客规则自动生成) 9.收款责任专业线(云客系统隐藏模块) 10.云售前人员(云客系统隐藏模块)
        //11.已开票金额(不推送,云链系统的已开票金额包含了收据金额，逻辑错误，只需要汇总类型为发票的金额即可) 12.




    }

    /**
     * 获取合同性质的ID
     * 由于老接口，默认值是7f83719a-fce8-11e4-bed8-00155d02c832，因此保留
     *
     * @param  $contract json ERP传来的合同参数
     * @return string
     */
    private function getContractPropertyId($contract)
    {
        //合同性质ID ，老接口 --- 由于商机系统那边没有此字段，故默认为“云客签约-直属区域”
        $result = '7f83719a-fce8-11e4-bed8-00155d02c832';
        if (isset($contract['contract_nature']) && !empty($contract['contract_nature'])){
            $propertyId = ContractPropertyRepository::getPropertyIdByName(trim($contract['contract_nature']));
            if($propertyId != false){
                $result = $propertyId;
            }
        }

        return $result;
    }

    /**
     * 获取合同的签署公司ID
     *
     * @param  $contract  json ERP传来的合同参数
     * @return string
     */
    private function getContractCompanyId($contract)
    {
        $result = '593d3902-006a-11e5-bed8-00155d02c832';   //合同签署公司ID 由于商机系统那边没有此字段，故默认为“明源云客”
        if (isset($contract['sign_buname']) && !empty($contract['sign_buname'])){
            $companyId = ContractCompanyRepository::getCompanyIdByName(trim($contract['sign_buname']));
            if($companyId != false){
                $result = $companyId;
            }
        }

        return $result;
    }

    /**
     * 获取合同小类的ID
     *
     * @author Chenjy01
     * @since  2017-08-10
     * @param  $contract  json ERP传来的合同参数
     * @return string
     */
    private function getContractCategoryId($contract)
    {
        $result = '62f81bf4-fcf4-11e4-bed8-00155d02c832';
        if (isset($contract['contract_type']) && !empty($contract['contract_type'])){
            $categoryId = ContractLittlerCategoryRepository::getLittlerCategoryIdByName(trim($contract['contract_type']));
            if($categoryId != false){
                $result = $categoryId;
            }
        }

        return $result;
    }

    /**
     * 获取租户的合同合同授权
     * @param null $org_id
     */
    public function actionGetOrganizationContractDetail($org_id = null)
    {
//        $data = $this->_contractService->getOrganizationContractDetail($org_id);
//        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
        $this->exportJson(false, '接口废弃', '接口废弃');
    }

    /**
     * 获取合同  业务来源
     *
     * @param  string $type 合同类型
     * @return string
     */
    private function getContractFromFinance($type)
    {
        switch ($type) {
            case $this->yunkeFinance:
            case $this->mingyuanFinance:
                $result = 1;
                break;
            default:
                $result = 1;
                break;
        }

        return $result;
    }

    /**
     * 获取合同  财务来源
     *
     * @param $type
     * @return string
     */
    private function getContractFromPerformanceFinance($type)
    {
        switch ($type) {
            case $this->yunkeFinance:
            case $this->mingyuanFinance:
                $result = 1;
                break;
            default:
                $result = 1;
                break;
        }

        return $result;
    }


    /**
     * 更新结算金额
     *
     * @param   $contract array 合同参数
     * @return  mixed
     */
    private function updateBalanceAmount($contract)
    {
        return \Yii::$app->contractDB->createCommand()
            ->update('myscrm_contract_manage', ['balance_amount' => $contract['balance_amount']], 'contract_id = :contract_id' )
            ->bindValue(':contract_id', $contract['contract_id'])
            ->execute();
    }

    /**
     * 联营会签归档生成进货合同接口
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     */
    public function actionAddAssociateContract() {
        $contractData = Yii::$app->request->request('contract');
        $contractInfo = json_decode($contractData, true);
        // 合同

        if(isset($contractInfo['contract_id']) && $contractInfo['contract_id']){
            $contract = $this->_contractService->getContractManageBySignId($contractInfo['contract_id']);
            if($contract){
                $this->exportJson(false, -1, '合同已经存在');
            }
        }

        $contract = $this->_contractService->getAssociateContractParams($contractInfo, 0);
        if (!$contract['company_id']) {
            $this->exportJson($contract['sign_buname'], -1, '合同系统不存在此签署公司');
        }


        // 合同产品
        $productInfo = $this->getContractProductParams('add');
        foreach ($productInfo as $key => $value) {
            //如果云客系统没有某个产品 则返回失败并提示
            if (!isset($value['application_id']) || empty($value['application_id'])) {
                $this->exportJson($productInfo, -1, "产品(id)不存在云客系统中，请双方沟通");
            }
            $productInfo[$key]['created_by']     = 'AssociateCountersign';
            $productInfo[$key]['modified_by']    = 'AssociateCountersign';
        }

        // 文档
        $docInfo = $this->getContractDocParams('add');
        foreach ($docInfo as $key => $value) {
            $docInfo[$key]['created_by']     = 'AssociateCountersign';
            $docInfo[$key]['modified_by']    = 'AssociateCountersign';
        }

        //录入
        $result = $this->_contractService->doInsertFromBusinessSystem($contract, [], $productInfo, [], $docInfo);

        //如果成功 返回合同id 失败 返回 false
        if ($result) {
            $res =  $contract['contract_id'];
        }else {
            $res = false;
        }

        $this->exportJson($res, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }


    /**
     * 标的物同步至合同系统接口
     */
    public function actionAddDocumentInfo(){
        $docs = $this->getDocumentParams();
        $result = $this->_contractService->doSyncDocument($docs);
        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }


    /**
     * 标的物同步至合同系统接口数据格式化
     * @return array
     */
    private function getDocumentParams(){
        $filesData = Yii::$app->request->request('FileList');
        $filesList = json_decode($filesData,true);
        $collections = array();
        foreach ($filesList as $files){
            $document = array();
            $document['document_id'] = $files['FileGUID'];
            $document['document_name'] = $files['FileName'];
            $document['document_ext_name'] = '';
            $document['document_path'] = $files['NetWorkUrl'];
            $document['business_id'] = $files['ContractGUID'];
            $document['created_by'] = $files['CreatorName'];
            $document['created_on'] = $files['CreateTime'];
            $document['document_type'] = 4;
            $document['out_file_id'] = $files['OutFileID'];
            $document['creator_id'] = $files['CreatorGUID'];
            $document['recipient_id'] = $files['ReceiveUserGUID'];
            $document['received_by'] = $files['ReceiveUser'];
            $document['received_on'] = $files['ReceiveDate'];
            $document['is_sign'] = $files['IsSignName'].'';
            $document['contract_code'] = $files['ContractCode'];
            $document['document_old_name'] = $files['FileOldName'];
            $document['document_new_name'] = $files['FileNewName'];
            $document['opportunities_id'] = $files['OpportunitiesGUID'];
            $document['document_size'] = $files['FileSize'];
            $document['document_group'] = $files['FileGroup'];
            $document['bop_file_type'] = $files['BopFileType'];
            $collections[] = $document;
        }
        return $collections;
    }


    /**
     * 提供订单产品的接口
     *
     * @return json data 
     * FileList[{
     * "OrderGUID":'"5tc4f6a5-1d45-4119-936f-fcb544834tgh"'订单GUID（主键）每次开通记录的id
     * "ContractGUID":'"6hc4f6a5-1d45-4119-936f-fcb54482bctg"'合同GUID 
     * "ProductGUID": "4ec4f6a5-1d45-4119-936f-fcb54482bcff",//产品GUID
     * "ProductName": "明源云客在线开盘服务",//产品名称   
     * "Num": 2,//授权项目数
     * "RentTime": "2018-03-26 10:21:18",//开通时间    
     * "JsAmount": "10500.00",//结算金额
     * }]
     */
    public function actionGetOrderInfo(){
        set_time_limit(0);
        $data = array();
        $ContractGuid = Yii::$app->request->request('ContractGuid');
        $beginTime = Yii::$app->request->request('beginTime');
        $endTime = Yii::$app->request->request('endTime');
        $orders = $this->_contractService->getOrdersInfo($ContractGuid,$beginTime,$endTime);
        $data['data'] = $orders;
        $this->json($data);
    }

    /**
     * 租户
     *
     */
    public function actionSyncOrderKey(){
        $data = Yii::$app->request->request('data');
        $data = json_decode($data,true);
        $result = $this->_contractService->updateAuthorizeOrderInfo($data);
        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionUpdateErpContractCode(){
        $contracts = $this->_contractService->getIllegalErpContract();
        $data = array('success'=>array(),'fault'=>array());

        foreach ($contracts as $contract){
            $entity = ContractManageRepository::getContractManageByErpContractCode($contract['erp_contract_code']);
            if(!$entity){
                $data['fault'][$contract['erp_contract_code']] = '';
                continue;
            }
            $erp_contract_id = ErpInterfaceService::getErpContractGUID($entity->erp_contract_code);
            if($entity->erp_contract_id){
                $data['fault'][$entity->erp_contract_code] = $entity->erp_contract_id;
                continue;
            }
            if(empty($erp_contract_id)){
                $data['fault'][$entity->erp_contract_code] = $entity->erp_contract_id;
                continue;
            }
            $entity->erp_contract_id = $erp_contract_id;

            $res = $entity->save();
            if($res){
                $data['success'][$entity->erp_contract_code] = $entity->erp_contract_id;
            }else{
                $data['fault'][$entity->erp_contract_code] = $entity->erp_contract_id;
            }
        }
        $this->json($data);
    }

    public function actionGetSubjectMatterInfo(){
        $ContractGuid = Yii::$app->request->post('ContractGuid');
        if(empty($ContractGuid)){
            $this->exportJson([], -1, '缺少必要的参数');
        }
        $beginTime = '';
        $endTime = '';
        $ContractInfo = $this->_contractService->getContractListByTime($beginTime, $endTime, $ContractGuid);
        $ContractProduct = $this->_contractService->getProductInfoByTime($beginTime, $endTime, $ContractGuid);
        $ContractOrders = $this->_contractService->getOrdersInfo($ContractGuid,$beginTime,$endTime);
        $data['Base'] = $ContractInfo[0];
        $data['Products'] = $ContractProduct[0];
        $data['Orders'] = $ContractOrders[0];
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }


    public function actionGetDirectContract(){
        $beginTime = Yii::$app->request->post('beginTime');
        $endTime = Yii::$app->request->post('endTime');

        $list = $this->_contractService->getDirectContract($beginTime,$endTime);

        $this->exportJson($list, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionGetDirectContractPayment(){
        $beginTime = Yii::$app->request->post('beginTime');
        $endTime = Yii::$app->request->post('endTime');

        $list = $this->_contractService->getDirectContractPayment($beginTime,$endTime);

        $this->exportJson($list, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }
}
